#-*- coding:utf-8 -*-
from userinfo.models import Userinfo
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from userinfo.forms import Userform,Usereditform
import smtplib
from email.mime.text import MIMEText
from email.Header import Header
import time,md5,sha,random
from Graduation_web.settings import WEB_SERVER_HOST
from Graduation_web.views import get_msg_count
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

@login_required
def userinfo_action(request):
    username = request.session['user']
    msg_count = get_msg_count(username)
    userinfo = Userinfo.objects.get(username=username)
    activity = userinfo.activity
    gender = userinfo.gender
    id = str(userinfo.ident)
    id = list(id)
    id[8:15] = '*******'
    id = ''.join(id)
    email = userinfo.email
    telephone = userinfo.telephone
    address = userinfo.address
    form = Userform()
    return render_to_response('user.html', locals())

@login_required
def userinfo_submit_action(request):
    username = request.session['user']
    msg_count = get_msg_count(username)
    if request.method == 'POST':
        form = Userform(request.POST)
        if form.is_valid():
            form_cd = form.cleaned_data
            verify = getverify()
            ret = send(form_cd.get('email'), username, verify)
            if ret:
                Userinfo.objects.filter(username=username).update(gender=form_cd.get('gender'), ident=form_cd.get('ident'), email=form_cd.get('email'), telephone=form_cd.get('telephone'), address=form_cd.get('address'),verify=security(verify))
                success_msg = '请查收邮件激活！'
                return render_to_response('success.html',locals())
            else:
                erro_msg = '验证邮件发送失败！'
                return render_to_response('erro.html',locals())
        else:
            error = True
            form = Userform()
            return render_to_response('user.html',locals())
    return HttpResponseRedirect('/home')

def activity_action(request):
    if request.method == 'GET':
        username = request.GET.get('username','')
        msg_count = get_msg_count(username)
        verify = request.GET.get('verify','')
        ret = Userinfo.objects.filter(username = username,verify = security(verify),activity='0')
        if len(ret):
            ret.update(activity='1',verify='')
            success_msg = '激活成功！'
            return render_to_response('success.html',locals())
        else:
            erro_msg = '没有注册信息，或已经注册过了！'
            return render_to_response('erro.html',locals())
        
@login_required
def edit_user_action(request):
    username = request.session.get('user','')
    msg_count = get_msg_count(username)
    userinfo = Userinfo.objects.get(username = username)
    gender = userinfo.gender
    id = str(userinfo.ident)
    id = list(id)
    id[8:15] = '*******'
    id = ''.join(id)
    email = userinfo.email
    telephone = userinfo.telephone
    address = userinfo.address
    activity = userinfo.activity
    form = Usereditform()
    if request.method == 'POST':
        form = Usereditform(request.POST)
        if form.is_valid():
            form_cd = form.cleaned_data
            t_mail = form_cd.get('email')
            if email == t_mail:
                Userinfo.objects.filter(username=username).update(telephone=form_cd.get('telephone'), address=form_cd.get('address'))
                success_msg = '修改成功！'
                return render_to_response('success.html',locals())
            else:
                verify = getverify()
                if send(form_cd.get('email'), username, verify):
                    Userinfo.objects.filter(username=username).update(email=form_cd.get('email'), telephone=form_cd.get('telephone'), address=form_cd.get('address'),verify=security(verify),activity='0')                
                    success_msg = '您修改了邮箱，请登录邮箱重新激活！'
                    return render_to_response('success.html',locals())
                else:
                    erro_msg = '验证邮件发送失败！'
                    return render_to_response('erro.html',locals())
        else:
            error = True
            return render_to_response('edit.html',locals())
    else:
        if activity == '0':
            return HttpResponseRedirect('/userinfo')
        return render_to_response('edit.html',locals())

def forget_passwd_action(request):
    if request.method == 'POST':
        t_username = request.POST.get('username',0)
        email = request.POST.get('email',0)
        if not t_username or not email:
            error = '不能有空白项！'
            return render_to_response('forget_passwd.html',locals())
        try:
            Userinfo.objects.get(username = t_username,email = email)
        except:
            error = '该邮箱与用户不匹配！'
            return render_to_response('forget_passwd.html',locals())
        verify = getverify()
        Userinfo.objects.filter(username = t_username,email = email).update(verify = verify)
        send(email, t_username, verify, 'getpasswd')
        success_msg = '请登录邮箱重置密码'
        return render_to_response('success.html',locals())
    else:
        return render_to_response('forget_passwd.html',locals())

def getpasswd_action(request):
    if request.method == 'POST':
        t_username = request.POST.get('username',0)
        passwd1 = request.POST.get('passwd1',0)
        passwd2 = request.POST.get('passwd2',0)
        if not t_username or passwd1 != passwd2 or not passwd1:
            error = '两次密码输入不一致！'
            return render_to_response('getpasswd.html',locals())
        user = User.objects.get(username = t_username)
        user.set_password(passwd1)
        user.save()
        success_msg = '密码设置成功！'
        return render_to_response('success.html',locals())
    else:
        t_username = request.GET.get('username',0)
        verify = request.GET.get('verify',0)
        try:
            Userinfo.objects.get(username = t_username,verify = verify)
        except:
            error_msg = '错误的链接！'
            return render_to_response('erro.html',locals())
        return render_to_response('getpasswd.html',locals())

def getverify():
    return '%s%s' % (time.time(),random.randrange(999999999))

def security(m_str):
    md5_value = md5.new(m_str).hexdigest()
    return sha.new(md5_value).hexdigest()

def send(send_to,username,verify,activity='activity'):
    try:
        char_set = 'utf-8'
        title = '注册激活'
        activity_link = 'http://%s/%s?username=%s&verify=%s' % (WEB_SERVER_HOST,activity,username,verify)
        text = '''
        你好，%s
        
            感谢您的注册，请点击下面链接激活您的账号！
    %s
    
    此邮件为系统发送，请勿回复！
        '''.decode(char_set) % (username,activity_link)
        message = MIMEText(text,_charset = char_set)
        message['subject'] = Header(title,char_set)
        message['from'] = 'relax-activity@qq.com'
        message['to'] = send_to
        message['text'] = text
        smtp = smtplib.SMTP("smtp.qq.com:25")
        smtp.login("relax-activity","jiangdebin")
        smtp.sendmail("relax-activity@qq.com",send_to,message.as_string())
        smtp.quit()
        return True
    except Exception:
        return False